#include "GUI.h"
#include "simmsg.h"
#include <stdio.h>
#include <math.h>
#define RECOMMENDED_MEMORY (1024L * 5)

int waveData[104] = {0};
int mul_x = 50;
int mul_y = 50;
int offset_x = 0;
int offset_y = 0;

GUI_MEMDEV_Handle mendev;

char* getString(int i, char* str){
    char buf[10] = {0};
    sprintf(buf, "%d%s", i, str);
    return buf;
}

void drawWave(){
    int i, temp;
    GUI_Clear();
    GUI_SetPenSize(1);
    GUI_SetColor(GUI_WHITE);
    GUI_DrawRect(5, 5, 315, 215);
    GUI_DrawHLine(110, 5, 315);
    GUI_DrawVLine(160, 5, 215);
    GUI_SetLineStyle(GUI_LS_DOT);
    GUI_SetColor(GUI_CYAN);
    for(i = 0; i < 9; i++){
        if(i != 4){
            temp = 26 + i * 21;
            GUI_DrawLine(5, temp, 315, temp);
            temp = 36 + i * 31;
            GUI_DrawLine(temp, 5, temp, 215);
        }
    }

    GUI_SetLineStyle(GUI_LS_SOLID);
    GUI_SetColor(GUI_YELLOW);

    GUI_MoveTo(5, waveData[0] + 110);
    for(i = 1; i < 104; i++){
        GUI_DrawLineTo(5 + i * 3, waveData[i] + 110);
    }

    GUI_SetColor(GUI_WHITE);
    GUI_DispStringAt("vol", 5, 222);
    GUI_DispStringAt("offset", 80, 222);
    GUI_DispStringAt("time", 160, 222);
    GUI_DispStringAt("offset", 240, 222);

    GUI_SetColor(GUI_MAGENTA);
    GUI_DispStringAt(getString(mul_x,"mv"), 25, 222);
    GUI_DispStringAt(getString(offset_x,"mv"), 120, 222);
    GUI_DispStringAt(getString(mul_y,"ms"), 190, 222);
    GUI_DispStringAt(getString(offset_y,"ms"), 280, 222);
}

void updateWave(){
    int i;
    for(i = 0; i < 104; i++){
        waveData[i] = (int)(sin((double)(i + offset_y) * mul_y / 10 * 3.14 / 180) * mul_x + offset_x);
        if(waveData[i] < -105) waveData[i] = -105;
        if(waveData[i] > 105) waveData[i] = 105;
    }
}

void MainTask(void) {
    GUI_Init();
    if (GUI_ALLOC_GetNumFreeBytes() < RECOMMENDED_MEMORY) {
        GUI_ErrorOut("Not enough memory available.");
        return;
    }
    mendev = GUI_MEMDEV_Create(0, 0, 319, 239);
    GUI_MEMDEV_Select(mendev);

    updateWave();
    drawWave();

    while(1){
        int msg;
        if(msg = getMsg()){
            switch(msg){
            case 1:
                offset_x = getData();
                updateWave();
                break;
            case 2:
                offset_y = getData();
                updateWave();
                break;
            case 3:
                mul_x = getData();
                updateWave();
                break;
            case 4:
                mul_y = getData();
                updateWave();
                break;
            case 100:
                drawWave();
                GUI_MEMDEV_CopyToLCD(mendev);
                break;
            }
        }
    }
}
